package com.itaq.cheetah.serviceB.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itaq.cheetah.serviceA.config.http.HttpRequest;
import com.itaq.cheetah.serviceA.model.dto.SsoRespDto;
import com.itaq.cheetah.serviceA.model.result.WrapperResult;
import com.itaq.cheetah.serviceA.model.vo.SsoUserInfo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cheetah
 * @date 2022/7/22
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/sso")
public class SsoController {

    /**
     * 获取票据，并请求ServiceA 获取用户信息
     *
     * @param ticket 票据
     * @return 返回地址供sso跳转
     * @throws JsonProcessingException 异常
     */
    @GetMapping("/url")
    public WrapperResult<SsoRespDto> sso(@RequestParam("ticket") String ticket) throws JsonProcessingException {
        log.info("收到票据：{}", ticket);
        //1.根据ticket换取ServiceA用户信息
        Map<String, Object> param = new HashMap<>(1);
        param.put("ticket", ticket);
        String ssoUrl = "http://localhost:8081/getUser";
        String s = HttpRequest
                .get(ssoUrl)
                .queryMap(param)
                .connectTimeout(Duration.ofSeconds(120))
                .readTimeout(Duration.ofSeconds(120))
                .execute()
                .asString();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        WrapperResult<SsoUserInfo> ssoUserInfoWrapperResult = objectMapper.readValue(s, new TypeReference<WrapperResult<SsoUserInfo>>() {
        });
        log.info("ticket登录结果：{}", new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(ssoUserInfoWrapperResult));
        //2.获取到用户信息之后同步到本地数据库
        log.info("获取用户信息同步数据库");
        //3.生成token返回链接
        log.info("生成token");
        SsoRespDto respDto = new SsoRespDto();
        //将ServiceA要跳转的地址返给ServiceA并携带 ServiceB 的token
        respDto.setRedirectUrl("http://localhost:8082/index?token=123456");
        WrapperResult<SsoRespDto> success = WrapperResult.success(respDto);
        log.info(new ObjectMapper().writeValueAsString(success));
        return success;
    }


}
